<?php
// +----------------------------------------------------------------------
// | HkCms 上下页标签、上一页标签、下一页标签
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\index\taglib\huicms;

use think\facade\Cache;
use think\helper\Str;

class TagPreNext extends Base
{

    /**
     * 上篇下篇生成A标签
     *
     * @param $tag
     *
     * @return string
     */
    public function preNextHtml($tag)
    {
        $catinfo = (new \app\common\model\Category)->getCateInfo($tag['catid']);
        if ( ! empty($catinfo['data']) && ! empty($catinfo['data']["model_id"])) {
            $info = controller($catinfo['data'], function ($obj, $model, $category) use ($tag) {
                if ($tag['type'] == 'pre') {
                    return $obj->whereIn('cate_id', $category['childids'])->where(['status' => 1])->where('id', '<',
                        $tag['id'])->order(["id" => "DESC"])->find();
                } else {
                    return $obj->whereIn('cate_id', $category['childids'])->where(['status' => 1])->where('id', '>',
                        $tag['id'])->order(["id" => "asc"])->find();
                }

            }, 'category');
            if (empty($info)) {
                return '';
            }
            $info = $info->append(["url"])->toArray();

            $title = $info[$tag['field']] ?? '';
            $title = $tag['len'] ? (Str::length($title) > $tag['len'] ? Str::substr($title, 0,
                    (int)$tag['len']).$tag['dot'] : $title) : $title;

            return '<a href="'.$info['url'].'" '.((empty($tag['target'])) ? '' : 'target="'.$tag['target'].'"').' title="'.$info[$tag['field']].'">'.$title.'</a>';
        } else {
            return '';
        }
    }

}
